const fs =require('fs');
const url =require('url');
const io =require('socket.io');
const http =require('http');
const mysql = require('mysql');	

const regs = require('regs');//这个引错了


	let db = mysql.createPool({host:'localhost',port:3306,username:'root',password:'',database:'20181210'})
let	httpServer=http.createServer((request,response)=>{
	let {pathname,query} = url.parse(req.url,true)
		fs.readFile(pathname,(err,data)=>{
			if(err){
				response.writeHeader(404);
				response.write('not found');
			}
			else{
				response.write(data);
			}
			response.end();
		})
	});

	httpServer.listen(8080);


let wsServer=io.listen(httpServer);

	wsServer.on('connection',(sock)=>{
		let cur_user = '';
		let cur_id =0;




		//注册
		sock.on('reg',(user,pass)=>{
			if(!regs.username.test(user)){
				sock.emit('reg_rs',1,'用户名不符合规则');
			}else if(!regs.password.test(pass)){
				sock.emit('reg_rs',1,'密码不符合规则');
			}else{
				db,query(`SELECT ID FROM user_data WHERE username='${user}'`,(err,data)=>{
					if(err){
						sock.emit('reg_rs',1,'数据库有问题')
					}else if(data.length>0){
						sock.emit('reg_rs',1,'用户名已存在')
					}else{
						db.query(`INSERT INTO user_data (username,password,online) VALUES('${user}',${pass},0)`,err=>{
							if(err){
								sock.emit('reg_rs',1,'数据库有问题')
							}else{
								sock.emit('reg_rs',1,'注册成功')
							}
						});
					}
				});
			}
		});
		//登录
		sock.on('login',(user,pass)=>{
			db.query(`SELECT ID,password FROM user_data WHERE username='${user}'`,(err,data)=>{
				if(err){
					sock.emit('login_rs',1,'数据库有问题');
				}else if(data.length==0){
					sock.emit('login_rs',1,'用户不存在');
				}else if(data[0].password!=pass){
					sock.emit('login_rs',1,'密码输入有误');
				}else{
					db.query(`UPDATA user_data SET online=1 WHERE ID=${data[0].ID}`,err=>{
						if(err){
							sock.emit('login_rs',1,'数据库有问题');
						}else{
							sock.emit('login_rs',0,'登录成功');
							cur_user=user;
							cur_id = data[0].ID;
						}
					})
				}
			})
		})

		//离线
		sock.on('disconnect',function(){
			
			db.query(`UPDATA user_data SET online=0 WHERE ID=${cur_id}`,err=>{
				if(err){
					console.log('服务器有问题');
				}else{
					console.log('用户离线');
					cur_user='';
					cur_id =0;
				}
			})
		})


	})
